<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="900px"
    :before-close="handleClose"
    class="edit-equipment-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="dialog-content">
      <!-- 设备信息概览 -->
      <div class="equipment-overview" v-if="formData.equipmentId">
        <div class="overview-item">
          <span class="label">设备ID:</span>
          <span class="value">{{ formData.equipmentId }}</span>
        </div>
        <div class="overview-item">
          <span class="label">当前状态:</span>
          <el-tag :type="getStatusTagType(formData.equipmentStatus)" size="small">
            {{ getStatusText(formData.equipmentStatus) }}
          </el-tag>
        </div>
      </div>

      <el-form
        ref="editForm"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="edit-form"
        :validate-on-rule-change="false"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">
              <i class="el-icon-info"></i>
              基本信息
            </h3>
            <div class="section-divider"></div>
          </div>
          
          <div class="form-grid">
            <div class="form-row">
              <div class="form-col">
                <el-form-item label="所属小区" prop="communityId" required>
                  <el-select
                    v-model="formData.communityId"
                    placeholder="请选择小区"
                    style="width: 100%"
                    clearable
                    filterable
                    :loading="communityLoading"
                  >
                    <el-option
                      v-for="community in communityList"
                      :key="community.communityId"
                      :label="community.communityName"
                      :value="community.communityId"
                    />
                  </el-select>
                </el-form-item>
              </div>
              
              <div class="form-col">
                <el-form-item label="设备名称" prop="equipmentName" required>
                  <el-input
                    v-model="formData.equipmentName"
                    placeholder="请输入设备名称"
                    maxlength="50"
                    show-word-limit
                    clearable
                  />
                </el-form-item>
              </div>
            </div>

            <div class="form-row">
              <div class="form-col">
                <el-form-item label="设备类型" prop="equipmentCategory" required>
                  <el-select
                    v-model="formData.equipmentCategory"
                    placeholder="请选择设备类型"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="(label, value) in equipmentCategoryOptions"
                      :key="value"
                      :label="label"
                      :value="Number(value)"
                    />
                  </el-select>
                </el-form-item>
              </div>
              
              <div class="form-col">
                <el-form-item label="设备编码" prop="equipmentCode" required>
                  <el-input
                    v-model="formData.equipmentCode"
                    placeholder="请输入设备编码"
                    maxlength="30"
                    clearable
                  >
                    <template #prepend>
                      <i class="el-icon-barcode"></i>
                    </template>
                  </el-input>
                </el-form-item>
              </div>
            </div>

            <div class="form-row">
              <div class="form-col">
                <el-form-item label="安装地点" prop="installationLocation">
                  <el-input
                    v-model="formData.installationLocation"
                    placeholder="请输入安装地点"
                    maxlength="100"
                    clearable
                  />
                </el-form-item>
              </div>
              
              <div class="form-col">
                <el-form-item label="规格型号" prop="equipmentSpecification">
                  <el-input
                    v-model="formData.equipmentSpecification"
                    placeholder="请输入规格型号"
                    maxlength="50"
                    clearable
                  />
                </el-form-item>
              </div>
            </div>
          </div>
        </div>

        <!-- 设备状态与维护 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">
              <i class="el-icon-setting"></i>
              设备状态与维护
            </h3>
            <div class="section-divider"></div>
          </div>
          
          <div class="form-grid">
            <div class="form-row">
              <div class="form-col">
                <el-form-item label="设备状态" prop="equipmentStatus" required>
                  <el-select
                    v-model="formData.equipmentStatus"
                    placeholder="请选择设备状态"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="(label, value) in equipmentStatusOptions"
                      :key="value"
                      :label="label"
                      :value="Number(value)"
                    />
                  </el-select>
                </el-form-item>
              </div>
              
              <div class="form-col">
                <el-form-item label="保养周期" prop="maintenancePeriod">
                  <el-select
                    v-model="formData.maintenancePeriod"
                    placeholder="请选择保养周期"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="(label, value) in maintenancePeriodOptions"
                      :key="value"
                      :label="label"
                      :value="Number(value)"
                    />
                  </el-select>
                </el-form-item>
              </div>
            </div>

            <div class="form-row">
              <div class="form-col">
                <el-form-item label="设备材料" prop="material">
                  <el-input
                    v-model="formData.material"
                    placeholder="请输入设备材料"
                    maxlength="50"
                    clearable
                  />
                </el-form-item>
              </div>
              
              <div class="form-col">
                <el-form-item label="设备重量" prop="weight">
                  <el-input
                    v-model="formData.weight"
                    placeholder="请输入设备重量"
                    type="number"
                    min="0"
                    step="0.1"
                    clearable
                  >
                    <template #append>KG</template>
                  </el-input>
                </el-form-item>
              </div>
            </div>
          </div>
        </div>

        <!-- 扩展信息 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">
              <i class="el-icon-document"></i>
              扩展信息
            </h3>
            <div class="section-divider"></div>
          </div>
          
          <div class="form-grid">
            <div class="form-row">
              <div class="form-col full-width">
                <el-form-item label="备注信息" prop="remarks">
                  <el-input
                    v-model="formData.remarks"
                    type="textarea"
                    placeholder="请输入备注信息"
                    :rows="3"
                    maxlength="200"
                    show-word-limit
                    resize="none"
                  />
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <div class="footer-left">
          <el-button @click="handleReset" :disabled="submitting">
            <i class="el-icon-refresh-left"></i>
            重置
          </el-button>
        </div>
        <div class="footer-right">
          <el-button @click="handleClose" :disabled="submitting">
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="submitting"
            :disabled="!isFormValid"
          >
            <i class="el-icon-check"></i>
            保存修改
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { equipmentApi } from '@/api/equipment'
import request, { communityRequest } from '@/utils/request'

export default {
  name: 'EditEquipmentDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    equipmentData: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue', 'success'],
  data() {
    return {
      // 表单数据
      formData: {
        equipmentId: '',
        communityId: '',
        installationLocation: '',
        equipmentName: '',
        equipmentCategory: null,
        equipmentCode: '',
        equipmentSpecification: '',
        equipmentStatus: 1,
        maintenancePeriod: null,
        material: '',
        weight: null,
        remarks: ''
      },
      
      // 原始数据备份
      originalData: {},
      
      // 表单验证规则
      formRules: {
        communityId: [
          { required: true, message: '请选择所属小区', trigger: 'change' }
        ],
        equipmentName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' },
          { min: 2, max: 50, message: '设备名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        equipmentCategory: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ],
        equipmentCode: [
          { required: true, message: '请输入设备编码', trigger: 'blur' },
          { min: 3, max: 30, message: '设备编码长度在 3 到 30 个字符', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9_-]+$/, message: '设备编码只能包含字母、数字、下划线和连字符', trigger: 'blur' }
        ],
        equipmentStatus: [
          { required: true, message: '请选择设备状态', trigger: 'change' }
        ],
        weight: [
          { pattern: /^(0|[1-9]\d*)(\.\d+)?$/, message: '请输入有效的重量数值', trigger: 'blur' }
        ]
      },
      
      // 小区列表
      communityList: [],
      communityLoading: false,
      
      // 提交状态
      submitting: false,
      
      // 选项配置
      equipmentCategoryOptions: {
        1: '电梯',
        2: '空调',
        3: '消防设备',
        4: '照明设备',
        5: '给排水设备',
        6: '安防设备',
        7: '广告设备',
        8: '其他设备'
      },
      
      equipmentStatusOptions: {
        1: '正常',
        2: '故障',
        3: '维修中',
        4: '停用'
      },
      
      maintenancePeriodOptions: {
        1: '每月',
        3: '每季度',
        6: '每半年',
        12: '每年',
        24: '每两年'
      }
    }
  },
  
  computed: {
    visible: {
      get() {
        return this.modelValue
      },
      set(val) {
        this.$emit('update:modelValue', val)
      }
    },
    
    // 对话框标题
    dialogTitle() {
      return this.formData.equipmentId ? '编辑设备信息' : '新增设备信息'
    },
    
    // 表单是否有效
    isFormValid() {
      return this.formData.communityId && 
             this.formData.equipmentName && 
             this.formData.equipmentCategory && 
             this.formData.equipmentCode && 
             this.formData.equipmentStatus
    },
    
    // 是否有数据变更
    hasDataChanged() {
      return JSON.stringify(this.formData) !== JSON.stringify(this.originalData)
    }
  },
  
  watch: {
    equipmentData: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.initFormData(newVal)
        }
      },
      immediate: true,
      deep: true
    },
    
    visible(newVal) {
      if (newVal) {
        this.loadCommunityList()
      }
    }
  },
  
  methods: {
    // 初始化表单数据
    initFormData(data) {
      this.formData = {
        equipmentId: data.equipmentId || '',
        communityId: data.communityId || '',
        installationLocation: data.installationLocation || '',
        equipmentName: data.equipmentName || '',
        equipmentCategory: data.equipmentCategory || null,
        equipmentCode: data.equipmentCode || '',
        equipmentSpecification: data.equipmentSpecification || '',
        equipmentStatus: data.equipmentStatus || 1,
        maintenancePeriod: data.maintenancePeriod || null,
        material: data.material || '',
        weight: data.weight || null,
        remarks: data.remarks || ''
      }
      
      // 备份原始数据
      this.originalData = JSON.parse(JSON.stringify(this.formData))
    },
    
    // 加载小区列表
    async loadCommunityList() {
      if (this.communityList.length > 0) return
      
      this.communityLoading = true
      try {
        const response = await communityRequest({
          url: '/community/selcomm',
          method: 'get'
        })
        if (response.code === 200) {
          this.communityList = response.data || []
        } else {
          this.$message.error(response.message || '加载小区列表失败')
        }
      } catch (error) {
        console.error('加载小区列表失败:', error)
        this.$message.error('加载小区列表失败')
      } finally {
        this.communityLoading = false
      }
    },
    
    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        1: 'success',  // 正常
        2: 'danger',   // 故障
        3: 'warning',  // 维修中
        4: 'info'      // 停用
      }
      return typeMap[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      return this.equipmentStatusOptions[status] || '未知'
    },
    
    // 重置表单
    handleReset() {
      this.$confirm('确定要重置表单吗？所有修改将丢失。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.initFormData(this.originalData)
        this.$nextTick(() => {
          if (this.$refs.editForm) {
            this.$refs.editForm.clearValidate()
          }
        })
        this.$message.success('表单已重置')
      }).catch(() => {
        this.$message.info('已取消重置')
      })
    },
    
    // 提交表单
    async handleSubmit() {
      try {
        // 表单验证
        await this.$refs.editForm.validate()
        
        // 检查是否有数据变更
        if (!this.hasDataChanged) {
          this.$message.info('没有检测到数据变更')
          return
        }
        
        this.submitting = true
        
        // 准备提交数据，处理空值
        const submitData = {
          equipmentId: this.formData.equipmentId,
          communityId: this.formData.communityId,
          equipmentName: this.formData.equipmentName.trim(),
          equipmentCategory: this.formData.equipmentCategory,
          equipmentCode: this.formData.equipmentCode.trim(),
          equipmentStatus: this.formData.equipmentStatus,
          maintenancePeriod: this.formData.maintenancePeriod,
          // 处理数值字段，空字符串转为null
          weight: this.formData.weight && this.formData.weight.toString().trim() !== '' ? Number(this.formData.weight) : null,
          // 处理字符串字段，空字符串转为null
          installationLocation: this.formData.installationLocation && this.formData.installationLocation.trim() !== '' ? this.formData.installationLocation.trim() : null,
          equipmentSpecification: this.formData.equipmentSpecification && this.formData.equipmentSpecification.trim() !== '' ? this.formData.equipmentSpecification.trim() : null,
          material: this.formData.material && this.formData.material.trim() !== '' ? this.formData.material.trim() : null,
          remarks: this.formData.remarks && this.formData.remarks.trim() !== '' ? this.formData.remarks.trim() : null
        }
        
        console.log('提交数据:', submitData)
        
        const response = await equipmentApi.updateEquipment(submitData)
        if (response.code === 200) {
          this.$message.success('设备信息更新成功')
          this.$emit('success')
          this.handleClose()
        } else {
          this.$message.error(response.message || '设备信息更新失败')
        }
      } catch (error) {
        if (error.message) {
          // 表单验证错误
          return
        }
        console.error('提交失败:', error)
        this.$message.error('设备信息更新失败，请稍后重试')
      } finally {
        this.submitting = false
      }
    },
    
    // 关闭弹框
    handleClose() {
      // 如果有未保存的更改，提示用户
      if (this.hasDataChanged && !this.submitting) {
        this.$confirm('检测到未保存的更改，确定要关闭吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.doClose()
        }).catch(() => {
          this.$message.info('已取消关闭')
        })
      } else {
        this.doClose()
      }
    },
    
    // 执行关闭操作
    doClose() {
      this.visible = false
      // 重置表单
      this.$nextTick(() => {
        if (this.$refs.editForm) {
          this.$refs.editForm.resetFields()
        }
        // 清空数据
        this.formData = {
          equipmentId: '',
          communityId: '',
          installationLocation: '',
          equipmentName: '',
          equipmentCategory: null,
          equipmentCode: '',
          equipmentSpecification: '',
          equipmentStatus: 1,
          maintenancePeriod: null,
          material: '',
          weight: null,
          remarks: ''
        }
        this.originalData = {}
      })
    }
  }
}
</script>

<style scoped>
.edit-equipment-dialog {
  max-height: 85vh;
  overflow-y: auto;
}

.dialog-content {
  padding: 0 10px;
}

/* 设备信息概览 */
.equipment-overview {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  padding: 15px 20px;
  margin-bottom: 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.overview-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.overview-item .label {
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

.overview-item .value {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

/* 表单样式 */
.edit-form {
  max-width: 100%;
}

.form-section {
  margin-bottom: 35px;
  background: #fafbfc;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e4e7ed;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title i {
  color: #409EFF;
  font-size: 18px;
}

.section-divider {
  flex: 1;
  height: 2px;
  background: linear-gradient(90deg, #409EFF 0%, transparent 100%);
  margin-left: 15px;
}

.form-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-row {
  display: flex;
  gap: 25px;
  align-items: flex-start;
}

.form-col {
  flex: 1;
  min-width: 0;
}

.form-col.full-width {
  flex: 2;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

.footer-left {
  display: flex;
  gap: 10px;
}

.footer-right {
  display: flex;
  gap: 10px;
}

/* 表单项样式调整 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

:deep(.el-input__inner:focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-select .el-input__inner) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-input-group__prepend) {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #909399;
}

:deep(.el-input-group__append) {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #909399;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #66b1ff 0%, #409EFF 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

:deep(.el-button--primary:disabled) {
  background: #c0c4cc;
  transform: none;
  box-shadow: none;
}

/* 加载状态 */
:deep(.el-loading-mask) {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .edit-equipment-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .equipment-overview {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }
  
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .form-col {
    margin-bottom: 0;
  }
  
  .dialog-footer {
    flex-direction: column;
    gap: 15px;
  }
  
  .footer-left,
  .footer-right {
    width: 100%;
    justify-content: center;
  }
  
  .footer-left .el-button,
  .footer-right .el-button {
    flex: 1;
    max-width: 120px;
  }
}

@media (max-width: 480px) {
  .dialog-content {
    padding: 0 5px;
  }
  
  .form-section {
    padding: 15px;
    margin-bottom: 20px;
  }
  
  .section-title {
    font-size: 14px;
  }
  
  .overview-item {
    flex-direction: column;
    gap: 5px;
    text-align: center;
  }
}

/* 动画效果 */
.form-section {
  animation: slideInUp 0.3s ease-out;
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.equipment-overview {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 滚动条样式 */
.edit-equipment-dialog::-webkit-scrollbar {
  width: 6px;
}

.edit-equipment-dialog::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.edit-equipment-dialog::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.edit-equipment-dialog::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
